import { create } from 'zustand';
import { persist, createJSONStorage } from 'zustand/middleware';
import { subscribeWithSelector } from 'zustand/middleware';
import { invoke } from '@tauri-apps/api/core';

// 数据状态接口
interface DataState {
  // 应用配置
  appConfig: AppConfig | null;

  // 用户数据
  users: User[];

  // 日志数据
  logs: LogEntry[];

  // 缓存数据
  cache: Record<string, CacheItem>;

  // 同步状态
  syncStatus: SyncStatus;

  // 最后更新时间
  lastUpdated: Record<string, number>;
}

interface AppConfig {
  id: string;
  theme: string;
  language: string;
  autoStart: boolean;
  minimizeToTray: boolean;
  notifications: boolean;
  shortcuts: Record<string, string>;
  createdAt: string;
  updatedAt: string;
}

interface User {
  id: number;
  username: string;
  email?: string;
  createdAt: string;
  updatedAt: string;
  isActive: boolean;
}

interface LogEntry {
  id?: number;
  level: string;
  message: string;
  component?: string;
  metadata?: any;
  createdAt: string;
}

interface CacheItem {
  data: any;
  timestamp: number;
  ttl: number;
}

interface SyncStatus {
  syncing: boolean;
  lastSync: number | null;
  error: string | null;
}

// 数据操作接口
interface DataActions {
  // 应用配置操作
  loadAppConfig: () => Promise<void>;
  updateAppConfig: (config: Partial<AppConfig>) => Promise<void>;
  resetAppConfig: () => Promise<void>;

  // 用户操作
  loadUsers: () => Promise<void>;
  addUser: (
    user: Omit<User, 'id' | 'createdAt' | 'updatedAt'>
  ) => Promise<void>;
  updateUser: (id: number, updates: Partial<User>) => Promise<void>;
  deleteUser: (id: number) => Promise<void>;

  // 日志操作
  loadLogs: (limit?: number, level?: string) => Promise<void>;
  addLog: (log: Omit<LogEntry, 'id' | 'createdAt'>) => Promise<void>;
  clearLogs: () => Promise<void>;

  // 缓存操作
  setCache: (key: string, data: any, ttl?: number) => void;
  getCache: (key: string) => any | null;
  clearCache: (key?: string) => void;

  // 同步操作
  syncData: () => Promise<void>;
  setSyncStatus: (status: Partial<SyncStatus>) => void;

  // 通用操作
  setLastUpdated: (key: string) => void;
  clearData: () => void;
}

type DataStore = DataState & DataActions;

// 默认状态
const defaultState: DataState = {
  appConfig: null,
  users: [],
  logs: [],
  cache: {},
  syncStatus: {
    syncing: false,
    lastSync: null,
    error: null,
  },
  lastUpdated: {},
};

// 创建数据 store
export const useDataStore = create<DataStore>()(
  subscribeWithSelector(
    persist(
      (set, get) => ({
        ...defaultState,

        // 应用配置操作
        loadAppConfig: async () => {
          try {
            const config = await invoke<AppConfig>('get_app_config');
            set({ appConfig: config });
            get().setLastUpdated('appConfig');
          } catch (error) {
            console.error('Failed to load app config:', error);
            throw error;
          }
        },

        updateAppConfig: async updates => {
          try {
            const { appConfig } = get();
            if (!appConfig) throw new Error('No app config loaded');

            const updatedConfig = { ...appConfig, ...updates };
            await invoke('set_app_config', { config: updatedConfig });
            set({ appConfig: updatedConfig });
            get().setLastUpdated('appConfig');
          } catch (error) {
            console.error('Failed to update app config:', error);
            throw error;
          }
        },

        resetAppConfig: async () => {
          try {
            await invoke('reset_app_config');
            await get().loadAppConfig();
          } catch (error) {
            console.error('Failed to reset app config:', error);
            throw error;
          }
        },

        // 用户操作
        loadUsers: async () => {
          try {
            const users = await invoke<User[]>('get_users');
            set({ users });
            get().setLastUpdated('users');
          } catch (error) {
            console.error('Failed to load users:', error);
            throw error;
          }
        },

        addUser: async userData => {
          try {
            const user = await invoke<User>('create_user', { user: userData });
            set(state => ({ users: [...state.users, user] }));
            get().setLastUpdated('users');
          } catch (error) {
            console.error('Failed to add user:', error);
            throw error;
          }
        },

        updateUser: async (id, updates) => {
          try {
            const user = await invoke<User>('update_user', { id, updates });
            set(state => ({
              users: state.users.map(u => (u.id === id ? user : u)),
            }));
            get().setLastUpdated('users');
          } catch (error) {
            console.error('Failed to update user:', error);
            throw error;
          }
        },

        deleteUser: async id => {
          try {
            await invoke('delete_user', { id });
            set(state => ({
              users: state.users.filter(u => u.id !== id),
            }));
            get().setLastUpdated('users');
          } catch (error) {
            console.error('Failed to delete user:', error);
            throw error;
          }
        },

        // 日志操作
        loadLogs: async (limit, level) => {
          try {
            const logs = await invoke<LogEntry[]>('get_logs', { limit, level });
            set({ logs });
            get().setLastUpdated('logs');
          } catch (error) {
            console.error('Failed to load logs:', error);
            throw error;
          }
        },

        addLog: async logData => {
          try {
            const log = await invoke<LogEntry>('add_log', { log: logData });
            set(state => ({ logs: [log, ...state.logs] }));
          } catch (error) {
            console.error('Failed to add log:', error);
            throw error;
          }
        },

        clearLogs: async () => {
          try {
            await invoke('clear_logs');
            set({ logs: [] });
            get().setLastUpdated('logs');
          } catch (error) {
            console.error('Failed to clear logs:', error);
            throw error;
          }
        },

        // 缓存操作
        setCache: (key, data, ttl = 5 * 60 * 1000) => {
          set(state => ({
            cache: {
              ...state.cache,
              [key]: {
                data,
                timestamp: Date.now(),
                ttl,
              },
            },
          }));
        },

        getCache: key => {
          const { cache } = get();
          const item = cache[key];

          if (!item) return null;

          const now = Date.now();
          if (now - item.timestamp > item.ttl) {
            // 缓存过期，清除
            get().clearCache(key);
            return null;
          }

          return item.data;
        },

        clearCache: key => {
          if (key) {
            set(state => {
              const { [key]: _, ...rest } = state.cache;
              return { cache: rest };
            });
          } else {
            set({ cache: {} });
          }
        },

        // 同步操作
        syncData: async () => {
          const { setSyncStatus } = get();

          setSyncStatus({ syncing: true, error: null });

          try {
            // 同步所有数据
            await Promise.all([
              get().loadAppConfig(),
              get().loadUsers(),
              get().loadLogs(),
            ]);

            setSyncStatus({
              syncing: false,
              lastSync: Date.now(),
              error: null,
            });
          } catch (error) {
            setSyncStatus({
              syncing: false,
              error: error instanceof Error ? error.message : String(error),
            });
            throw error;
          }
        },

        setSyncStatus: status => {
          set(state => ({
            syncStatus: { ...state.syncStatus, ...status },
          }));
        },

        // 通用操作
        setLastUpdated: key => {
          set(state => ({
            lastUpdated: { ...state.lastUpdated, [key]: Date.now() },
          }));
        },

        clearData: () => {
          set(defaultState);
        },
      }),
      {
        name: 'data-store',
        storage: createJSONStorage(() => localStorage),
        partialize: state => ({
          appConfig: state.appConfig,
          cache: state.cache,
          lastUpdated: state.lastUpdated,
        }),
      }
    )
  )
);

// 选择器
export const useAppConfig = () => useDataStore(state => state.appConfig);
export const useUsers = () => useDataStore(state => state.users);
export const useLogs = () => useDataStore(state => state.logs);
export const useSyncStatus = () => useDataStore(state => state.syncStatus);

// 操作选择器
export const useDataActions = () =>
  useDataStore(state => ({
    loadAppConfig: state.loadAppConfig,
    updateAppConfig: state.updateAppConfig,
    resetAppConfig: state.resetAppConfig,
    loadUsers: state.loadUsers,
    addUser: state.addUser,
    updateUser: state.updateUser,
    deleteUser: state.deleteUser,
    loadLogs: state.loadLogs,
    addLog: state.addLog,
    clearLogs: state.clearLogs,
    setCache: state.setCache,
    getCache: state.getCache,
    clearCache: state.clearCache,
    syncData: state.syncData,
    setSyncStatus: state.setSyncStatus,
    setLastUpdated: state.setLastUpdated,
    clearData: state.clearData,
  }));

// 自动同步
let syncInterval: number | null = null;

export const startAutoSync = (intervalMs = 5 * 60 * 1000) => {
  if (syncInterval) {
    clearInterval(syncInterval);
  }

  syncInterval = setInterval(() => {
    const { syncData, syncStatus } = useDataStore.getState();
    if (!syncStatus.syncing) {
      syncData().catch(console.error);
    }
  }, intervalMs) as unknown as number;
};

export const stopAutoSync = () => {
  if (syncInterval) {
    clearInterval(syncInterval);
    syncInterval = null;
  }
};

export type { AppConfig, User, LogEntry, CacheItem, SyncStatus };
export default useDataStore;
